from pymongo import MongoClient
from datetime import datetime
import uuid

# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['hakka_miniprogram']

# 反馈工单集合
feedback_collection = db['feedback_orders']

class FeedbackOrder:
    @staticmethod
    def create_order(data):
        """创建新工单"""
        order_id = str(uuid.uuid4())
        order = {
            'id': order_id,
            'userId': data.get('userId'),
            'type': data.get('type'),
            'buildingName': data.get('buildingName'),
            'description': data.get('description'),
            'images': data.get('images', []),
            'phone': data.get('phone', ''),
            'location': data.get('location', {}),
            'status': data.get('status', '审核中'),  # 审核中、已派单、已接单、修复中、已完成
            'createTime': datetime.now(),
            'updateTime': datetime.now(),
            'handlerId': '',  # 处理人员ID
            'processLogs': []  # 处理日志
        }
        
        result = feedback_collection.insert_one(order)
        return order_id if result.inserted_id else None
    
    @staticmethod
    def get_order_by_id(order_id):
        """通过ID获取工单"""
        return feedback_collection.find_one({'id': order_id})
    
    @staticmethod
    def get_orders_by_user(user_id):
        """获取用户的所有工单"""
        return list(feedback_collection.find({'userId': user_id}).sort('createTime', -1))
    
    @staticmethod
    def update_order_status(order_id, status, handler_id='', log=''):
        """更新工单状态"""
        update_data = {
            'status': status,
            'updateTime': datetime.now()
        }
        
        if handler_id:
            update_data['handlerId'] = handler_id
            
        # 添加处理日志
        if log:
            feedback_collection.update_one(
                {'id': order_id},
                {'$push': {
                    'processLogs': {
                        'time': datetime.now(),
                        'status': status,
                        'handlerId': handler_id,
                        'log': log
                    }
                }}
            )
        
        result = feedback_collection.update_one(
            {'id': order_id},
            {'$set': update_data}
        )
        
        return result.modified_count > 0
    
    @staticmethod
    def get_all_orders(status=None, page=1, limit=10):
        """获取所有工单，支持状态筛选和分页"""
        query = {}
        if status:
            query['status'] = status
            
        skip = (page - 1) * limit
        return {
            'orders': list(feedback_collection.find(query).sort('createTime', -1).skip(skip).limit(limit)),
            'total': feedback_collection.count_documents(query)
        }